package com.htfyun.guowenagingscreen;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.htfyun.eink.EinkShowMode;
import com.htfyun.eink.EinkUtils;

import java.lang.ref.WeakReference;

public class MainActivity extends FullScreenBaseActivity {

    private int screenViewChangedCount = 0;
    private final static int SCREEN_VIEW_CHANGE_MAX_COUNT = 6;
    private int[] colorResIds;
    private LinearLayout linearLayoutContainer;

    private TextView txtTime;

    private Context mContext;

    private MyHandler myHandler;

    private long startTime;

    private final static long TEST_TIME = 4 * 60 * 60 * 1000L;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);

        mContext = this;

        myHandler = new MyHandler(this);

        linearLayoutContainer = (LinearLayout) findViewById(R.id.linearLayoutContainer);

        txtTime = (TextView) findViewById(R.id.txtTime);

        EinkUtils.setEinkUpdateModeWithView(txtTime, EinkShowMode.GL);

        colorResIds = getResources().getIntArray(R.array.color_gray_level);

        screenViewChangedCount = 0;

        linearLayoutContainer.removeAllViews();
        linearLayoutContainer.setBackgroundColor(Color.WHITE);

        linearLayoutContainer.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                showDialog();
                return true;
            }
        });
    }

    private void updateScreen() {

        screenViewChangedCount++;
        if (screenViewChangedCount >= SCREEN_VIEW_CHANGE_MAX_COUNT) {
            screenViewChangedCount = 0;

        }

        if (screenViewChangedCount == 0) {

            linearLayoutContainer.removeAllViews();
            linearLayoutContainer.setBackgroundColor(Color.WHITE);

        } else if (screenViewChangedCount == 1) {

            linearLayoutContainer.removeAllViews();
            linearLayoutContainer.setBackgroundColor(Color.BLACK);

        } else {

            final int pos = screenViewChangedCount - 2;

            setChildView((pos & 0x1) != 0, (pos & 0x2) != 0);
        }

        myHandler.sendEmptyMessageDelayed(MyHandler.MSG_TEST_SCREEN, MyHandler.PERIOD_TEST_SCREEN);

        long now = System.currentTimeMillis();
        String time = TimeStringUtils.makeTimeString(this, (now - startTime) / 1000);

        Log.e("song", "time = " + time);
        txtTime.setText(getString(R.string.aging_test_time, time));
    }

    private void setChildView(boolean colorRevert, boolean vertical) {

        linearLayoutContainer.removeAllViews();

        linearLayoutContainer.setOrientation(vertical ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);

        for (int i = 0; i < colorResIds.length; i++) {
            View view = new View(mContext);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            int color = colorResIds[i];
            if (colorRevert) {
                color = colorResIds[colorResIds.length - 1 - i];
            }
            view.setBackgroundColor(color);
            view.setClickable(false);
            linearLayoutContainer.addView(view, lp);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        FTUtils.startFTFloat(this);

        myHandler.removeMessages(MyHandler.MSG_TEST_SCREEN);
        myHandler.removeMessages(MyHandler.MSG_TEST_CHECK);

        EinkAgingScreenSharedPref.setExitTime_ms(this, System.currentTimeMillis());

    }

    @Override
    protected void onResume() {
        super.onResume();

        FTUtils.stopFTFloat(this);

        myHandler.sendEmptyMessage(MyHandler.MSG_TEST_SCREEN);
        myHandler.sendEmptyMessage(MyHandler.MSG_TEST_CHECK);

        startTime = System.currentTimeMillis();

        EinkAgingScreenSharedPref.setStartTime_ms(this, startTime);
    }

    private void checkIfTimeout() {
        long now = System.currentTimeMillis();
        if (now - startTime >= TEST_TIME) {
            finishWithOK();
        }
    }

    private void showDialog() {
        new ViewDialogFragment().show(getFragmentManager(),
                R.string.screen_test,
                R.string.item_exit_test,
                new ViewDialogFragment.Callback() {
                    @Override
                    public void onClick() {
                        finishWithOK();
                    }
                },
                null);
    }

    protected void finishWithOK() {
        ActivityCompat.finishAfterTransition(this);
    }


    private static class MyHandler extends Handler {

        private static final int MSG_TEST_SCREEN = 10;
        private static final int PERIOD_TEST_SCREEN = 5000;

        private static final int MSG_TEST_CHECK = 20;
        private static final int PERIOD_TEST_CHECK = 60 * 1000;

        private final WeakReference<MainActivity> activityWeakReference;

        private MyHandler(MainActivity activity) {
            super(Looper.getMainLooper());

            activityWeakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            //弱引用会在下一次gc时回收
            MainActivity activity = activityWeakReference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case MSG_TEST_SCREEN:
                    activity.updateScreen();
                    break;
                case MSG_TEST_CHECK:
                    activity.checkIfTimeout();
                    sendEmptyMessageDelayed(msg.what, PERIOD_TEST_CHECK);
                    break;
                default:
                    break;
            }

        }
    }

}
